package jp.chiheisen.httpserver;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class Handler implements HttpHandler {
	/** インデックスファイル */
	private static final List<String> INDEX_FILE_LIST = Arrays.asList(new String[]{"index.html", "index.htm"});
	
	/** カレントパス */
	private final File currentPath;
	/** カレントパス(正規) */
	private final String currentCanonicalPath;
	
	public Handler() throws IOException{
		this.currentPath = new File(System.getProperty("user.dir"));
		this.currentCanonicalPath = currentPath.getCanonicalPath();
	}
	
	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String path = exchange.getRequestURI().getPath();
		System.out.println(path);
		File file = new File(currentPath, path);
		
		InputStream requestBody = exchange.getRequestBody();
		while(requestBody.read() != -1);
		requestBody.close();
		
		Response response = new Response(exchange);
		
		if(file.exists() && !file.isHidden() && valid(file)){
			if(file.isFile()){
				response.send(file);
			}else if(file.isDirectory()){
				File[] index = getIndexFile(file);
				if(index.length > 0){
					response.send(index[0]);
				}else{
					response.sendNotFound();
				}
			}
		}else{
			response.sendNotFound();
		}
		
		exchange.getResponseBody().close();
	}

	private File[] getIndexFile(File dir) {
		assert dir.isDirectory();
		
		File[] file = dir.listFiles(new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				return INDEX_FILE_LIST.contains(name);
			}
		});
		
		return file;
	}
	
	private boolean valid(File file) throws IOException{
		// 有効なディレクトリへのアクセスか？ (ディレクトリトラバーサル対策)
		return file.getCanonicalPath().startsWith(currentCanonicalPath);
	}
}
